package com.toumy.service;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.toumy.domain.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Component
public class ImgService {
    @Autowired
    private COSClient cosClient;
    @Autowired
    private IBookService bookService;
    @Value("${cos.Bucket_name}")
    private String bucket_name;

    public boolean upload(int id, MultipartFile[] files) throws IOException {
        String imgNum;
        int i;

        for(i = 0;i<files.length;i++) {
            MultipartFile file = files[i];

            Book book = bookService.getById(id);
            if (book.getImg1() == null) {
                imgNum = "img1";
            } else if (book.getImg2() == null) {
                imgNum = "img2";
            } else if (book.getImg3() == null) {
                imgNum = "img3";
            } else {
                return false;
            }

            String name = file.getOriginalFilename();

            int typeLocation = name.lastIndexOf(".");
            String type = name.substring(typeLocation);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
            String time = simpleDateFormat.format(new Date());
            String uuid = UUID.randomUUID().toString().replace("-", "");

            String key = time + "/" + uuid + type;

            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentType("image/" + name.substring(typeLocation + 1));

            PutObjectRequest putObjectRequest = new PutObjectRequest(bucket_name, key, file.getInputStream(), objectMetadata);
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);

            if (putObjectResult == null)
                break;

            UpdateWrapper<Book> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("id", id).set(imgNum,key);
            bookService.update(null, updateWrapper);
        }

        return i == files.length;
    }

    public boolean delete(String[] keys){
        int i;
        int length = 0;

        for (String key:keys) {
            if (key != null)
                length++;
        }

        for(i = 0; i <length; i++) {
            String key = keys[i];
            boolean flag = cosClient.doesObjectExist(bucket_name, key);

            if (!flag)
                break;

            cosClient.deleteObject(bucket_name, key);
        }

        return i == length;
    }
}
